using System;

using Gonte.Reflection;

namespace Gonte
{
    /// <summary>
    /// Makes a copy of an object
    /// </summary>
    public static class ObjectCloner
    {
        #region Static Methods

        public static T Clone<T>(T @object)
        {
            return (T)Clone((Object)@object); // Cast to object to avoid calling the same method
        }

        public static Object Clone(Object @object)
        {
            if (@object is ICloneable)
            {
                return ((ICloneable)@object).Clone();
            }
            else if (@object is ValueType)
            {
                return @object;
            }
            else
            {
                return ReflectionClone(@object);
            }
        } 

        #endregion

        #region Helpers

        private static Object ReflectionClone(Object @object)
        {
            Type type = @object.GetType();
            Object clonedObject = ObjectFactory.CreateObject(type);

            TypeAccessor typeAccessor = TypeAccessor.GetTypeAccessor(type);

            foreach (string propertyName in typeAccessor.PropertyNames)
            {
                if (typeAccessor.IsPrimitive(propertyName))
                {
                    Object value = typeAccessor.GetValue(@object, propertyName);
                    typeAccessor.SetValue(clonedObject, propertyName, value);
                }

                // TODO: Clone complex objects
            }

            return clonedObject;
        } 

        #endregion
    }
}
